package com.lb.shopguide.ui.fragment.boss;

import android.graphics.Color;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.R;
import com.lb.shopguide.adapter.AdapterPointConfig;
import com.lb.shopguide.base.BaseCommonFragment;
import com.lb.shopguide.entity.PointConfigBean;
import com.lb.shopguide.event.boss.RookieSetPtPercentEvent;
import com.lb.shopguide.http.method.ApiMethodBoss;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.baselib.http.SimpleObserverOtherListener;
import com.lb.shopguide.ui.activity.BossMainActivity;
import com.lb.shopguide.ui.dialog.DialogSetPointConfig;
import com.lb.shopguide.ui.view.ClearTitleBar;
import com.lb.shopguide.util.json.JsonUtil;
import com.lb.shopguide.util.lb.BizUtil;
import com.trello.rxlifecycle2.android.FragmentEvent;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import okhttp3.RequestBody;

/**
 * Created by kang on 2017/12/27.
 */

public class FragmentPointPercent extends BaseCommonFragment implements SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.ctb)
    ClearTitleBar ctb;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;

    private ArrayList<PointConfigBean> pointConfigList;
    private PointConfigBean curPointConfigBean;

    private AdapterPointConfig mAdapter;
    private DialogSetPointConfig dialogSetPointConfig;



    public static FragmentPointPercent newInstance() {
        return new FragmentPointPercent();
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_point_percent;
    }

    @Override
    public void initData() {
        pointConfigList = new ArrayList<>();
        sendRequestGetPointSettingsInShop();
    }

    @Override
    public void initView() {
        noDataView = LayoutInflater.from(mContext).inflate(R.layout.layout_empty_view_boss, (ViewGroup) mRecyclerView.getParent(), false);
        errorView = LayoutInflater.from(mContext).inflate(R.layout.layout_error_view, (ViewGroup) mRecyclerView.getParent(), false);
        noDataView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onRefresh();
            }
        });
        errorView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onRefresh();
            }
        });

        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setColorSchemeColors(Color.rgb(253, 91, 89));
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mAdapter = new AdapterPointConfig(R.layout.item_point_config, pointConfigList);
        mRecyclerView.setAdapter(mAdapter);

        mAdapter.setOnSettingClickListener(new AdapterPointConfig.OnSettingClickListener() {
            @Override
            public void onSettingClick(PointConfigBean bean) {
                curPointConfigBean = bean;
                showDialog();
            }
        });

        ctb.setTvTitle("积分兑换比设置");
        ctb.setLeftImageSrc(R.drawable.iv_back);
        ctb.setOnLeftImageListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop();
            }
        });
    }

    @Override
    public void finishRefresh() {
        mSwipeRefreshLayout.setRefreshing(false);
        mAdapter.loadMoreComplete();
    }

    @Override
    public void sessionOutOfDate() {
        ((BossMainActivity) getActivity()).onSessionOutOfDate();
    }

    @Override
    public void requestError(String error) {
        ToastUtils.showShort(error);
        finishRefresh();
    }

    @Override
    public String getPageTag() {
        return FragmentPointPercent.class.getName();
    }

    private void sendRequestGetPointSettingsInShop() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    JsonArray jsonArrayPointConfig = JsonUtil.getJsonArrayFromMap(response.getReturnContent());
                    if (jsonArrayPointConfig.size() != 0) {
                        for (JsonElement obj : jsonArrayPointConfig) {
                            PointConfigBean bean = JsonUtil.getGson().fromJson(obj, PointConfigBean.class);
                            pointConfigList.add(bean);
                        }
                        mAdapter.setNewData(pointConfigList);
                    } else {
                        bindEmpty();
                    }
                    finishRefresh();
                }
            }
        };
        ApiMethodBoss.getPointSettingsInShop(new SimpleLbObserver(listener, otherListener),this,FragmentEvent.DESTROY_VIEW);
    }

    private void sendRequestSetPointConfig(int point) {
        HashMap hashMap = new HashMap();
        hashMap.put("money", point);
        hashMap.put("storeCode", curPointConfigBean.getStoreCode());
        hashMap.put("storeName", curPointConfigBean.getStoreName());
        hashMap.put("msrId", curPointConfigBean.getMsrId());
        RequestBody body = BizUtil.getBodyFromMap(hashMap);
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == (ResponseCode.RESPONSE_SUCCESS)) {
                    dialogSetPointConfig.dismiss();
                    LogUtils.d("config upload!!!!!!!!!!!!" );
                    refresh();
                    EventBus.getDefault().post(new RookieSetPtPercentEvent());
                }
            }
        };
        SimpleObserverOtherListener errorListener = new SimpleObserverOtherListener() {
            @Override
            public void onSessionOutOfDate() {

            }

            @Override
            public void onError(String error) {
                ToastUtils.showShort("设置积分兑换比失败" + error);
            }
        };
        ApiMethodBoss.setPointConfig(new SimpleLbObserver(listener, errorListener), body,this, FragmentEvent.DESTROY_VIEW);
    }

    private void showDialog() {
        dialogSetPointConfig = DialogSetPointConfig.getDialogSetPointConfig();
        dialogSetPointConfig.show(getFragmentManager(), getPageTag());
        dialogSetPointConfig.setOnSureClickListener(new DialogSetPointConfig.OnSureClickListener() {
            @Override
            public void onSure(int point) {
                sendRequestSetPointConfig(point);
            }
        });
    }

    private void bindEmpty() {
        pointConfigList.clear();
        mAdapter.setNewData(pointConfigList);

        mNoData = true;
        onRefresh();
    }

    @Override
    public void onRefresh() {
        mAdapter.setEnableLoadMore(false);
        if (mError) {
            mAdapter.setEmptyView(errorView);
            mError = false;
        } else {
            if (mNoData) {
                mAdapter.setEmptyView(noDataView);
                mNoData = false;
            } else {
                refresh();
            }
        }
    }

    private void refresh() {
        pointConfigList = new ArrayList<>();
        sendRequestGetPointSettingsInShop();
        LogUtils.d("refresh!!!!!!!!!!!!" );
    }
}
